/*
Copyright 2010 Johan Maasing

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nu.zoom.android.gdata.project.client.activity;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import nu.zoom.android.gdata.project.client.Intents;
import nu.zoom.android.gdata.project.client.R;
import nu.zoom.android.gdata.project.client.StandardMenuHandler;
import nu.zoom.android.gdata.project.client.UIUtilities;
import nu.zoom.android.gdata.project.client.WKC;
import nu.zoom.android.gdata.project.integration.ProjectHostingClient;
import nu.zoom.android.gdata.project.integration.ProjectHostingClient.IssueDetail;
import nu.zoom.android.gdata.project.integration.ProjectHostingClient.Link;
import nu.zoom.android.gdata.project.integration.ProjectHostingFactory;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.TextView;

/**
 * @author Johan Maasing
 * 
 */
public class ViewIssue extends Activity {
	private static final String LOG_TAG = WKC.LOG_TAG;
	private final ProjectHostingClient projectHostingClient;
	private final FeedRunner feedRunner;
	private Uri issueWebUri;
	private MenuItem viewWebItem;
	private ProjectHostingClient.IssueDetail issue;
	private final StandardMenuHandler standardMenuHandler;

	public ViewIssue() {
		super();
		projectHostingClient = ProjectHostingFactory.getClient();
		feedRunner = new FeedRunner(this);
		this.standardMenuHandler = new StandardMenuHandler(this);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewissue);

		final Intent intent = getIntent();
		final String action = intent.getAction();
		if (action != null) {
			if (Intent.ACTION_VIEW.equalsIgnoreCase(action)) {
				ProjectHostingClient.IssueDetail retainer = (IssueDetail) getLastNonConfigurationInstance();
				if (retainer != null) {
					issueResult(retainer);
				} else {
					feedRunner.run(intent.getData(), null);
				}
			} else {
				Log.d(LOG_TAG, "Unknown intent action: " + action);
			}
		} else {
			Log.d(LOG_TAG, "No action specified for activity.");
			UIUtilities.reportError(this, R.string.error_noaction, null);
			this.finish();
		}
		final String title = intent.getStringExtra(Intents.Extra.PROJECT_NAME);
		if (title != null) {
			setTitle(title);
		}
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return issue;
	}

	private void initGUI() {
		final TextView titleView = (TextView) findViewById(R.id.ViewIssueTitle);
		titleView.setText(issue.title);

		final WebView contentview = (WebView) findViewById(R.id.ViewIssueContent);
		String content = issue.content;

		content = content.replaceAll("\\n", "<br />");

		// See issue http://code.google.com/p/android/issues/detail?id=1733
		content = Uri.encode(content);
		contentview.getSettings().setDefaultTextEncodingName("utf-8");

		contentview.loadData(content, "text/html", "utf-8");

		final TextView starview = (TextView) findViewById(R.id.IssueStarTextView);
		starview.setText(Integer.toString(issue.stars));

		final TextView labelsview = (TextView) findViewById(R.id.IssueLabelsTextView);
		StringBuilder sb = new StringBuilder();
		if (issue.labels != null) {
			for (String label : issue.labels) {
				sb.append(label).append(";");
			}
		}
		labelsview.setText(sb);

		final TextView idview = (TextView) findViewById(R.id.IssueID);
		idview.setText(issue.id);

		final TextView statusview = (TextView) findViewById(R.id.IssueStatus);
		statusview.setText(issue.status);

		final TextView stateview = (TextView) findViewById(R.id.IssueState);
		stateview.setText(issue.state);

		final TextView publishedview = (TextView) findViewById(R.id.IssuePublished);
		if (issue.published != null) {
			String published = issue.published.trim();
			published = published.replaceAll("Z", "\\+0000$");
			final SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
			final DateFormat localizedDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
			try {
				final Date parse = dateParser.parse(published);
				publishedview.setText(localizedDateFormat.format(parse));
			} catch (ParseException e) {
				Log.e(LOG_TAG, "Unable to parse date string: " + published, e);
			}
		}

		if (issue.author != null) {
			final StringBuilder author = new StringBuilder();
			author.append(issue.author.name);
			TextView issueReportedBy = (TextView) findViewById(R.id.IssueReportedBy);
			issueReportedBy.setText(author);
		}

		for (final Link link : issue.links) {
			if ("alternate".equalsIgnoreCase(link.rel)) {
				issueWebUri = (link.href != null) ? Uri.parse(link.href) : null;
				if (viewWebItem != null) {
					viewWebItem.setEnabled(issueWebUri != null);
				}
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(final int id) {
		return standardMenuHandler.onCreateDialog(id);
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		standardMenuHandler.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.reloadandwebmenu, menu);
		viewWebItem = menu.findItem(R.id.viewwebmenuitem);
		viewWebItem.setEnabled(issueWebUri != null);
		getMenuInflater().inflate(R.menu.viewissuemenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		switch (item.getItemId()) {
			case R.id.reloadmenuitem: {
				feedRunner.run(getIntent().getData(), null);
				return true;
			}
			case R.id.viewwebmenuitem: {
				if (issueWebUri != null) {
					Intent viewProjectWeb = Intents.viewIssueWeb(issueWebUri);
					this.startActivity(viewProjectWeb);
				}
			}
			case R.id.viewcommentsmenuitem: {
				Intent intent = Intents.viewIssueComments(this, getIntent().getData(), issue.title);
				this.startActivity(intent);
			}
			default:
				return standardMenuHandler.onOptionsItemSelected(item);
		}
	}

	private void issueResult(final IssueDetail issue) {
		this.issue = issue;
		initGUI();
	}

	class FeedRunner extends UIUtilities.FeedRunner<ProjectHostingClient.IssueDetail, Void> {

		public FeedRunner(Activity activity) {
			super(activity);
		}

		@Override
		protected void result(final IssueDetail result) {
			issueResult(result);
		}

		@Override
		protected IssueDetail runInBackground(Uri uri, Void parameter) throws IOException {
			return projectHostingClient.getIssue(uri);
		}
	}
}
